<template>
    <div class="question-selector">
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="题目内容">
          <el-input v-model="searchForm.content" placeholder="请输入题目内容"></el-input>
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型">
            <el-option label="全部" value=""></el-option>
            <el-option label="单选题" value="single"></el-option>
            <el-option label="多选题" value="multiple"></el-option>
            <el-option label="判断题" value="judgment"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="searchForm.difficulty" placeholder="请选择难度">
            <el-option label="全部" value=""></el-option>
            <el-option label="简单" value="1"></el-option>
            <el-option label="中等" value="3"></el-option>
            <el-option label="困难" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 题目列表 -->
      <el-table :data="questionList" border style="width: 100%" @selection-change="handleSelectionChange" v-loading="loading">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="content" label="题目内容"></el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            {{ questionTypeText[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100">
          <template slot-scope="scope">
            <el-rate v-model="scope.row.difficulty" disabled :max="5"></el-rate>
          </template>
        </el-table-column>
        <el-table-column label="分值" width="120">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.score" :min="1" :max="100" size="mini" v-if="isSelected(scope.row)"></el-input-number>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.current"
        :page-sizes="[10, 20, 50]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        class="pagination"></el-pagination>
      
      <!-- 操作按钮 -->
      <div class="actions">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </div>
  </template>
  
  <script>
  import { fetchQuestionList } from '@/api/study-question'
  
  export default {
    name: 'QuestionSelector',
    props: {
      selectedQuestions: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        loading: false,
        searchForm: {
          content: '',
          type: '',
          difficulty: ''
        },
        questionList: [],
        selectedRows: [],
        questionTypeText: {
          single: '单选题',
          multiple: '多选题',
          judgment: '判断题'
        },
        pagination: {
          current: 1,
          size: 10,
          total: 0
        }
      }
    },
    created() {
      this.refreshList()
      // 初始化已选题目
      this.selectedRows = [...this.selectedQuestions]
    },
    methods: {
      // 刷新题目列表
      refreshList() {
        this.loading = true
        const params = {
          ...this.searchForm,
          page: this.pagination.current,
          size: this.pagination.size
        }
        fetchQuestionList(params).then(response => {
          this.questionList = response.data.items.map(q => {
            // 设置默认分值
            if (!q.score) {
              q.score = 5
            }
            return q
          })
          this.pagination.total = response.data.total
          // 设置已选题目
          this.$nextTick(() => {  
            this.questionList.forEach(row => {
              if (this.isSelected(row)) {
                this.$refs.table.toggleRowSelection(row, true)
              }
            })
          })
        }).catch(error => {
          console.error('获取题目列表失败:', error)
        }).finally(() => {
          this.loading = false
        })
      },
      // 搜索
      handleSearch() {
        this.pagination.current = 1
        this.refreshList()
      },
      // 重置搜索
      resetSearch() {
        this.searchForm = {
          content: '',
          type: '',
          difficulty: ''
        }
        this.handleSearch()
      },
      // 分页大小变化
      handleSizeChange(size) {
        this.pagination.size = size
        this.refreshList()
      },
      // 当前页变化
      handleCurrentChange(current) {
        this.pagination.current = current
        this.refreshList()
      },
      // 选择变化
      handleSelectionChange(selection) {
        const currentPageIds = new Set(this.questionList.map(q => q.id))
        const newSelectedMap = new Map()
        selection.forEach(row => {
          newSelectedMap.set(row.id, row)
        })
        this.selectedRows = this.selectedRows
          .filter(q => {
            // 保留不在当前页的已选题目
            if (!currentPageIds.has(q.id)) return true
            // 如果当前页有选中，则使用新的选择项（保留原有分数）
            if (newSelectedMap.has(q.id)) {
              const newRow = newSelectedMap.get(q.id)
              newRow.score = q.score // 保留原有分数
              return false // 过滤掉旧的，使用新的
            }
            // 当前页未选中的题目过滤掉
            return false
          })
          // 添加当前页新选择的题目
          .concat(Array.from(newSelectedMap.values()))
      },
      // 检查题目是否已选
      isSelected(row) {
        return this.selectedRows.some(q => q.id === row.id)
      },
      // 取消选择
      cancel() {
        this.$emit('cancel')
      },
      // 确认选择
      confirm() {
        this.$emit('confirm', this.selectedRows)
      }
    }
  }
  </script>
  
  <style scoped>
  .question-selector {
    padding: 10px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: center;
  }
  
  .actions {
    margin-top: 20px;
    text-align: right;
  }
  </style>